var express = require('express')
var router = express.Router()
var City = require('../models/city')

router.get('/city', (req, res) => {
  City.find({})
    .sort({ update_at: -1 })
    .then(citys => {
      res.json(citys)
    })
    .catch(err => {
      res.json(err)
    })
})
// 通过ObjectId查询单个信息
router.get('/city/:id', (req, res) => {
  City.findById(req.params.id)
    .then(city => {
      res.json(city)
    })
    .catch(err => {
      res.json(err)
    })
})



// 通过用户名查询单个信息 
router.get('/city/:poster',function(req,res){
  City.find({poster:decodeURI(req.params.poster)})
  .then(poster=>{
    res.json(poster)
   console.log(poster)
  
  })
  .catch(err =>{
    res.json(err)
  })
})


// 添加一个信息
router.post('/city', (req, res) => {
  //使用city model上的create方法储存数据
  City.create(req.body, (err, city) => {
    if (err) {
      res.json(err)
    } else {
      res.json(city)
    }
  })

})
//更新一个信息
router.put('/city/:id', (req, res) => {
  City.findOneAndUpdate({ _id: req.params.id }
    , {
      $set: {
        title: req.body.title,
        rating: req.body.rating,
        poster: req.body.poster,
        introduction: req.body.introduction
      }
    }, {
      new: true
    })
    .then(city => res.json(city))
    .catch(err => res.json(err))
})
//删除一个信息
router.delete('/city/:id', (req, res) => {
  City.findOneAndRemove({
    _id: req.params.id
  })
    .then(city => res.send(`删除成功:${city.cityName}`))
    .catch(err => res.json(err))
})


//删除用户信息
// router.delete('/users/:id', function (req, res) {
  // User.findByIdAndRemove({
    // _id: req.params.id
  // })
    // .then(user => res.send(`${mousers.username}删除成功`))
    // .catch(err => res.json(err))
// })
module.exports = router